import { CaretDownOutlined, CaretRightOutlined } from '@ant-design/icons';
import { Table } from 'antd';
import { useEffect, useState } from 'react';
import { tableLocale } from '@/tool/components/PageEmpty';
import { connect } from 'umi';
import tableColumns from './helper';
import styles from './index.less';

const TableShow = ({ dispatch, XJTableData }) => {
  const [declareList, setDeclareList] = useState([]);

  const changeDeclare = (id, field, value) => {
    setDeclareList((prevList) => {
      const existingItem = prevList.find((item) => item.id === id);

      if (existingItem) {
        return prevList.map((item) => (item.id === id ? { ...item, [field]: value } : item));
      } else {
        return [...prevList, { id, [field]: value }];
      }
    });
  };

  useEffect(() => {
    setDeclareList([]);
  }, [XJTableData]);

  useEffect(() => {
    dispatch({
      type: 'dayRollingTradeStragety/setDeclareList',
      payload: declareList,
    });
  }, [declareList]);

  return (
    <>
      <Table
        columns={tableColumns(XJTableData, changeDeclare)}
        dataSource={XJTableData}
        bordered
        locale={tableLocale}
        className={styles.strategyTable}
        pagination={false}
        rowKey="id"
        scroll={{ x: 793 }}
        expandable={{
          expandIcon: ({ expanded, onExpand, record }) => {
            if (record.children && record.children.length > 0) {
              return expanded ? (
                <CaretDownOutlined onClick={(e) => onExpand(record, e)} />
              ) : (
                <CaretRightOutlined onClick={(e) => onExpand(record, e)} />
              );
            }
            return null;
          },
        }}
      />
    </>
  );
};

export default connect(({ dayRollingTradeStragety }) => ({
  XJTableData: dayRollingTradeStragety.XJTableData,
}))(TableShow);
